package com.openingedu.mba.screen.activity.practice;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

import com.lurencun.android.support.ui.BackUIActivity;
import com.lurencun.android.support.v2.widget.ViewPager;
import com.lurencun.android.toolkit.util.ActivitySwitcher;
import com.openingedu.mba.R;
import com.openingedu.mba.common.AppSetting;
import com.openingedu.mba.common.CommConsts;
import com.openingedu.mba.entity.QuestionVO;
import com.openingedu.mba.persist.DataHelper;
import com.openingedu.mba.persist.DbQuestion;
import com.openingedu.mba.screen.adapter.CommonPracticeAdapter;
import com.openingedu.mba.service.PracticeService;
import com.openingedu.mba.util.PracticeHandler;

/**
 * 普通练习
 * 
 * @author unidw
 * 
 */
public class CommonPraticeActivity extends BackUIActivity {

	private static final String TAG = CommonPraticeActivity.class.getSimpleName();
	private Context mContext;
	private DataHelper dataHelper;
	private List<QuestionVO> questionList = new ArrayList<QuestionVO>();
	private Chronometer chronometer;
	private PracticeService practiceService;
	private Button prevBtn;
	private Button nextBtn;
	private Button finishBtn;
	private ViewPager container;
	private int practiceWay;

	@Override
	protected void onCreateEx(Bundle savedInstanceState) {
		mContext = this;
		practiceService = new PracticeService();
		Intent intent = getIntent();
		String title = intent.getStringExtra(AppSetting.MENU_TITLE);
		
		TextView titleView = (TextView) findViewById(R.id.app_title);
		titleView.setText(title);
		dataHelper = new DataHelper(mContext);
		chronometer = (Chronometer) findViewById(R.id.total_chronometer);
		prevBtn = (Button) findViewById(R.id.prev_btn);
		nextBtn = (Button) findViewById(R.id.next_btn);
		finishBtn = (Button) findViewById(R.id.finish_btn);
		
		
		practiceWay = intent.getIntExtra(AppSetting.PRACTICE_WAY, CommConsts.Practice.DEFAULT_WAY);
		if (practiceWay == CommConsts.Practice.PAPER_WAY) {
			// 试卷ID
			Integer paperID = intent.getIntExtra(CommConsts.Comm.PAPER_ID, -1);
			List<DbQuestion> dbQuestionList = practiceService.loadPaperQuestion(mContext, paperID);
			for (DbQuestion dbQuestion : dbQuestionList) {
				questionList.add(new QuestionVO(dbQuestion));
			}
		}
		else if (practiceWay == CommConsts.Practice.FAULT_WAY) {
			try {
				List<DbQuestion> dbQuestionList = practiceService.listFaultDbQuestion(mContext);
				for (DbQuestion dbQuestion : dbQuestionList) {
					questionList.add(new QuestionVO(dbQuestion));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		container = (ViewPager) findViewById(R.id.topic_container);
		CommonPracticeAdapter adapter = new CommonPracticeAdapter(this);
		adapter.setData(questionList);
		adapter.setHandler(mHandler);
		container.setAdapter(adapter);
		
		chronometer.setVisibility(View.VISIBLE);
		chronometer.setFormat("耗时：%s");
		chronometer.start();
		prevBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int current = container.getCurrentItem();
				if (current > 0) {
					container.setCurrentItem(container.getCurrentItem() - 1);
				}
				else {
					Toast.makeText(mContext, "已经是第一题", Toast.LENGTH_LONG).show();
				}
				
			}
		});

		nextBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int total = container.getAdapter().getCount();
				int current = container.getCurrentItem();
				if (current < total - 1) {
					container.setCurrentItem(container.getCurrentItem() + 1);
				}
				else {
					Toast.makeText(mContext, "已经是最后一题", Toast.LENGTH_LONG).show();
				}
				
			}
		});
		
		finishBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				boolean finish = true;
				for (QuestionVO question : questionList) {
					if (!question.isFinish()) {
						finish = false;
					}
				}
				
				// 没有完成，并且不是错误题模式
				if (!finish && practiceWay != CommConsts.Practice.FAULT_WAY) {
					showFinishConfirm();
				}
				else {
					viewReuslt();
				}
			}
		});
	}
	
	private void showFinishConfirm() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
		alertDialog.setTitle("提示");
		alertDialog.setMessage("您还有未完成的试题，现在就要结束练习吗？");
		alertDialog.setPositiveButton("结束",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						viewReuslt();
					}
				});
		alertDialog.setNegativeButton("继续练习",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
					}
				});
		alertDialog.show();
		
	}
	
	private void viewReuslt() {
		chronometer.stop();
		// 所用时间
		long elapsedMillis = SystemClock.elapsedRealtime() - chronometer.getBase();
		
		int correctNum = 0;
		int faultNum = 0;
		int totalNum = questionList.size();
		for (QuestionVO question : questionList) {
			if (question.isCorrect()) {
				correctNum++;
			}
			else {
				faultNum++;
			}
		}
		String[] keys = new String[] { AppSetting.MENU_TITLE, "correctNum", "faultNum", "totalNum", "elapsedMillis"};
		Object[] vals = new Object[] { "练习结果", correctNum, faultNum, totalNum, elapsedMillis};
		ActivitySwitcher.switchTo(CommonPraticeActivity.this, ResultActivity.class, keys, vals);
		finish();
	}
	
    /** 停止计时*/
    public void stopChronometer() {  
        chronometer.stop();
    }
    
    /** 重置*/  
    public void resetChronometer() {
        //setBase 设置基准时间  
        //设置参数base为SystemClock.elapsedRealtime()即表示从当前时间开始重新计时）。  
        chronometer.setBase(SystemClock.elapsedRealtime());
    }

	private PracticeHandler mHandler = new PracticeHandler() {

		@Override
		public void overPractice() {
			Log.i(TAG, "overPractice, stop chronometer.");
		}

		@Override
		public void faultOption(QuestionVO question, Integer faultOptionID) {
			Log.i(TAG, "faultOption......");
			try {
				// 如果不是错误练习模式, 失败试题存入错题库
				if (practiceWay != CommConsts.Practice.FAULT_WAY) {
					practiceService.saveFaultQuestion(mContext, dataHelper, question);
				}
			} catch (SQLException e) {
				e.printStackTrace();
				Log.e(TAG, "save fault question error. questionID=" + question.getId());
			}
		}

		@Override
		public void correctQuestion(QuestionVO question) {
			Log.i(TAG, "correctQuestion......");
			// TODO 如果是错误练习模式完成后提示移除错题库
			if (practiceWay == CommConsts.Practice.FAULT_WAY) {
				
			}
		}
	};

	@Override
	protected void overridePendingTransition(Activity activity) {
		activity.overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
	}

	@Override
	protected int getContentViewLayoutId() {
		return R.layout.random_practice;
	}

	@Override
	protected int getBackButtonResId() {
		return R.id.back_button;
	}

	@Override
	protected boolean isConfirmBack() {
		return true;
	}

	@Override
	protected String getTipMessage() {
		return AppSetting.TOPIC_BACK_TIP;
	}
}
